/**
 * Created Date: Friday, October 21st 2022, 10:26:11 pm
 * Author: CodingGorit
 * -----
 * Last Modified: Fri Oct 28 2022
 * Modified By: CodingGorit
 * -----
 * Copyright (c) 2022 fmin-courses
 * ------------------------------------
 * Javascript will save your soul!
 * 
 * 此为 mysql CRUD demo，务必导入 示例 sql 文件，以及在 config/default.json 中设置 env 为 dev
 */

const express = require('express');
import { IRouterConf } from "../../../..";
import { Request, Response, NextFunction } from 'express';
import { Result } from "../../../../../common/Result";
import { ResultCodeEnum, ResultMessageEnum } from "../../../../../enums/ResultEmums";
import { IResponse } from "../../../../../types";
import { getStudents, getStudentById } from "../../../../../service/ExamplesService";

const examples = express.Router();

// Example 查询学生信息

examples.get("/students", async function(req: Request, res: IResponse, next: NextFunction) {
    return res.sendResult(new Result(ResultCodeEnum.QUERY_SUCCESS, ResultMessageEnum.QUERY_SUCCESS, await getStudents(req.query)));
});

// http://localhost:1347/api/private/v1/examples/students  可以看到如下数据
// "code": 20002,
// "msg": "查询成功",
// "data": [
//   {
//     "stuId": "20172345",
//     "stuName": "张冲",
//     "stuAge": 22,
//     "classz": "大三 新闻3班"
//   },
//   {
//  ....    

// Example 根据 ID 查询学生信息
examples.get("/student/:id",  function(req: Request, res: IResponse, next: NextFunction) {
    getStudentById(req.params.id as unknown as number, (val: any, msg?: string) => {
        if (!val) {
            if (msg) {
                return res.sendResult(new Result(ResultCodeEnum.QUERY_FAILED, msg));
            } 
            return res.sendResult(new Result(ResultCodeEnum.QUERY_FAILED, ResultMessageEnum.QUERY_FAILED));
        } else {
            return res.sendResult(new Result(ResultCodeEnum.QUERY_SUCCESS, ResultMessageEnum.QUERY_SUCCESS, val));
        }
    });
});


// http://localhost:1347/api/private/v1/examples/student/3
// {
//     "code": 20002,
//     "msg": "查询成功",
//     "data": [
//       {
//         "stuId": "20172345",
//         "stuName": "张冲",
//         "stuAge": 22,
//         "classz": "大三 新闻3班"
//       }
//     ]
//   }
// {
//     "code": 30001,
//     "msg": "Student not found!",
//     "data": ""
//   }

// Example 新增一条学生信息
examples.post("/student");

// Example 根据 ID 删除
examples.delete("/student/:id");

// Example 根据 ID 更新一条数据
examples.patch("/student/:id");


const routes: Array<IRouterConf> = [{
    path: "/examples",
    router: examples
}];

export = routes;